package org.jeecg.modules.foc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import dm.jdbc.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.c.entity.MArea;
import org.jeecg.modules.c.entity.MDevice;
import org.jeecg.modules.c.entity.MRoom;
import org.jeecg.modules.c.entity.MSite;
import org.jeecg.modules.c.service.*;
import org.jeecg.modules.concat.FocConcat;
import org.jeecg.modules.foc.FocSpaceTreeDTO;
import org.jeecg.modules.foc.entity.FocDevice;
import org.jeecg.modules.foc.entity.FocPoint;
import org.jeecg.modules.foc.entity.FocSpace;
import org.jeecg.modules.foc.mapper.FocDeviceMapper;
import org.jeecg.modules.foc.mapper.FocSpaceMapper;
import org.jeecg.modules.foc.service.IFocDeviceService;
import org.jeecg.modules.foc.service.IFocPointService;
import org.jeecg.modules.foc.service.IFocSpaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * @Description: 空间管理
 * @Author: jeecg-boot
 * @Date: 2025-01-10
 * @Version: V1.0
 */
@Service
@Slf4j
@Lazy
public class FocSpaceServiceImpl extends ServiceImpl<FocSpaceMapper, FocSpace> implements IFocSpaceService {


    @Autowired
    private FocDeviceMapper focDeviceMapper;
    @Autowired
    private FocSpaceMapper focSpaceMapper;

    @Autowired
    private IMAreaService mAreaService;

    @Autowired
    private IMSiteService mSiteService;
    @Autowired
    private IMRoomService mRoomService;

    @Autowired
    private IFocDeviceService focDeviceService;


    @Autowired
    private IMDeviceService mDeviceService;
    @Autowired
    private RedisUtil redisUtil;



    @Override
    public void getSpaceTree(FocSpaceTreeDTO focSpaceTreeDTO) {
        //根据全局ID获取空间树结构
        QueryWrapper<FocSpace> queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_guid", focSpaceTreeDTO.getGuid());
        List<FocSpace> list = this.list(queryWrapper);
        if (CollectionUtil.isEmpty(list)) {
            //如果是叶子节点，则查询设备信息
            QueryWrapper<FocDevice> deviceQueryWrapper = new <FocDevice>QueryWrapper();
            deviceQueryWrapper.eq("parent_guid", focSpaceTreeDTO.getGuid());
            List<FocDevice> focDevices = focDeviceMapper.selectList(deviceQueryWrapper);
            //将设备信息赋值到子节点中
            List<FocSpaceTreeDTO> focSpaceTreeDTOS = BeanUtil.copyToList(focDevices, FocSpaceTreeDTO.class);
            focSpaceTreeDTOS.forEach(dto -> {
                dto.setType(6);
                dto.setSelectable(true);
            });
            focSpaceTreeDTO.setChildren(focSpaceTreeDTOS);
            return;
        }
        List<FocSpaceTreeDTO> focSpaceTreeDTOS = BeanUtil.copyToList(list, FocSpaceTreeDTO.class);
        for (FocSpaceTreeDTO focSpace : focSpaceTreeDTOS) {
            //递归获取空间树结构
            getSpaceTree(focSpace);
            focSpaceTreeDTO.setChildren(focSpaceTreeDTOS);
        }
    }

    @Override
    public void spaceToData() {

    }

    @Override
    public void toSpeaceConvert(FocSpace focSpace) {
        log.info("空间转换开始"+ JSONObject.toJSONString(focSpace));
        //判断修改类型为区域还是站点
        if (Objects.equals(3, focSpace.getType()) || Objects.equals(2, focSpace.getType()) || Objects.equals(1, focSpace.getType())) {
            //判断映射字段是否为空
            if (StringUtil.isNotEmpty(focSpace.getAreaid()) && StringUtil.isNotEmpty(focSpace.getAreaname())) {
                //新建C接口区域对象
                MArea mArea = new MArea();
                mArea.setAreaid(focSpace.getAreaid());
                mArea.setAreaname(focSpace.getAreaname());
                mArea.setScid(FocConcat.SCID);
                //判断是否有父级
                if (StringUtil.isNotEmpty(focSpace.getLastareaid())) {
                    mArea.setLastareaid(this.getOne(new QueryWrapper<FocSpace>().eq("guid", focSpace.getParentGuid())).getAreaid());
                }
                mAreaService.saveOrUpdate(mArea);
            }
        }
        if (Objects.equals(4, focSpace.getType())) {
            //判断是否需要转换,房间
            //新建局房id
            MSite mSite = new MSite();
            mSite.setScid(FocConcat.SCID);
            mSite.setSiteid(focSpace.getSiteid());
            mSite.setSitename(focSpace.getSitename());
            //如果局站上配置了区域，则以局站的区域为准
            if (StringUtil.isNotEmpty(focSpace.getAreaid())) {
                mSite.setAreaid(focSpace.getAreaid());
            } else {
                if (StringUtil.isNotEmpty(focSpace.getParentGuid())) {
                    mSite.setAreaid(this.getOne(new QueryWrapper<FocSpace>().eq("guid", focSpace.getParentGuid())).getAreaid());
                }
            }
            mSiteService.saveOrUpdate(mSite);

        }
        //5是机房
        if (Objects.equals(5, focSpace.getType())) {
            //新建房间
            MRoom mRoom = new MRoom();
            mRoom.setScid(FocConcat.SCID);
            mRoom.setRoomid(focSpace.getRoomid());
            mRoom.setRoomname(focSpace.getRoomName());
            if (StringUtil.isNotEmpty(focSpace.getParentGuid())) {
                mRoom.setSiteid(this.getOne(new QueryWrapper<FocSpace>().eq("guid", focSpace.getParentGuid())).getSiteid());
            }
            mRoomService.saveOrUpdate(mRoom);
            //如果机房的映射改变，则虽所有对应的设备，也要改变
            List<FocDevice> parentGuid = focDeviceMapper.selectList(new QueryWrapper<FocDevice>().eq("parent_guid", focSpace.getGuid()));
            parentGuid.forEach(focDevice -> {
                //判断如果设备的roomid不存在，则进行处理
                if (StringUtil.isEmpty(focDevice.getRoomid())) {
                    focDevice.setRoomid(focSpace.getRoomid());
                    focDeviceMapper.updateById(focDevice);
                }
            });

        }

    }

    @Override
    public void cancleMapping(FocSpace focSpace) {
        //取消映射，当为设备时，进行取消映射逻辑
        if (Objects.equals(6, focSpace.getType())) {
            //判断是否走取消映射的逻辑
            FocDevice focDevice = focDeviceService.getById(focSpace.getId());
          /*  QueryWrapper<FocPoint> focSignalQueryWrapper = new QueryWrapper<>();
                    focSignalQueryWrapper.eq("parent_guid", focDevice.getGuid());
                    focSignalQueryWrapper.isNotNull("mp_code");
                    List<FocPoint> focSignals = focPointService.list(focSignalQueryWrapper);
                    for (FocPoint focSignal : focSignals) {
                        focPointService.cancleMapping(focSignal);
                    }*/
                    UpdateWrapper focDeviceUpdateWrapper = new UpdateWrapper();
                    focDeviceUpdateWrapper.eq("guid", focDevice.getGuid());
                    focDeviceUpdateWrapper.set("device_new_id", null);
                    focDeviceUpdateWrapper.set("roomid", null);
                    focDeviceUpdateWrapper.set("room_name", null);
                    focDeviceUpdateWrapper.set("device_name", null);
                    focDeviceUpdateWrapper.set("deviceid", null);
                    focDeviceUpdateWrapper.set("mp_big_type", null);
                    focDeviceUpdateWrapper.set("mp_device_type", null);
                   // focDeviceUpdateWrapper.set("device_type", null);
                    focDeviceService.update(focDeviceUpdateWrapper);
                    //判断设备id是否还存在
                    long deviceid = focDeviceService.count(new QueryWrapper<FocDevice>().eq("deviceid", focDevice.getDeviceid()));
                    if (deviceid == 0) {
                        //删除c接口映射信息
                        mDeviceService.remove(new QueryWrapper<MDevice>().eq("devassestid", focDevice.getDeviceid()));
                    }


        //刷新缓存
            redisUtil.removeAll("foc:speace");

        }else {
            throw new RuntimeException("类型不是设备，取消失败");
        }


    }


}
